﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using SHomeWorkshop.LunarPresentation.Commands;

namespace SHomeWorkshop.LunarPresentation.Dialogs
{
    /// <summary>
    /// ReplaceDialog.xaml 的交互逻辑
    /// </summary>
    public partial class ReplaceDialog : Window
    {
        public ReplaceDialog()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            tbxFindText.Focus();

            Globals.SwitchInputMethod(true);
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            Find();
        }

        private string preFindKeyword = null;

        //在查找结果列表中当前正被选中的那个。
        private int findResultPoint = -1;

        private List<Expressions.BaseText> findResultList = new List<Expressions.BaseText>();

        private void Find()
        {
            if (Globals.selectedEditor == null)
            {
                MessageBox.Show("当前没有打开任何文档。", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            //分情况：

            //⑴如果本次点击时，“查找内容”关键字没有发生变化，则说明是延续上次查找。
            //⑵如果“查找内容”关键字发生了变化，说明要开始一次全新的查找。
            //　　找到后，生成一个新列表。



            if (preFindKeyword == null || tbxFindText.Text != preFindKeyword)
            {
                preFindKeyword = tbxFindText.Text;
                findResultList.Clear();
                findResultPoint = -1;

                //开启一个新查找。
                List<Expressions.BaseText> resultList = this.findResultList;
                Command.FindBaseTextInExpression(resultList, Globals.selectedEditor.RootPanel, tbxFindText.Text);
            }

            FindNext();
        }

        private Expressions.BaseText FindNext()
        {
            if (findResultList.Count > 0)
            {
                findResultPoint += 1;
                if (findResultPoint >= 0 && findResultPoint < findResultList.Count)
                {
                    Expressions.BaseText bt = findResultList[findResultPoint];
                    bt.Editor.SelectedExpression = bt;

                    AutoLoctaion(bt);

                    return bt;
                }
                else
                {
                    MessageBox.Show("没有更多的结果了！", Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return null;
                }
            }
            else
            {
                MessageBox.Show("未找到！", Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return null;
            }
        }

        private void AutoLoctaion(Expressions.BaseText bt)
        {
            if (bt == null) return;

            bt.InvalidateArrange();
            bt.UpdateLayout();

            Point ptBase = new Point(0, 0);
            Point startPt = bt.PointToScreen(ptBase);
            Point endPt = new Point(startPt.X + bt.ActualWidth, startPt.Y + bt.ActualHeight);

            //MessageBox.Show("startX:" + startPt.X.ToString() + "\r\n" +
            //    "startY:" + startPt.Y.ToString() + "\r\n" +
            //    "endX:" + endPt.X.ToString() + "\r\n" +
            //    "endY:" + endPt.Y.ToString());

            if (startPt.Y < this.ActualHeight + 10)
            {
                this.Left = startPt.X;
                this.Top = endPt.Y + 10;
            }
            else
            {
                this.Left = startPt.X;
                this.Top = startPt.Y - this.ActualHeight - 10;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            findResultList.Clear();
            findResultPoint = -1;
            tbxFindText.Text = "";
        }

        private void tbxFindText_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Enter:
                    {
                        Find(); break;
                    }
                case Key.Escape:
                    {
                        this.Close(); break;
                    }
                case Key.Tab:
                    {
                        tbxReplaceText.Focus();
                        break;
                    }
            }
        }

        private void tbxReplaceText_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Enter:
                    {
                        Find(); break;
                    }
                case Key.Escape:
                    {
                        this.Close(); break;
                    }
            }
        }

        private void btnReplace_Click(object sender, RoutedEventArgs e)
        {
            if (findResultPoint >= 0 && findResultPoint <= findResultList.Count - 1)
            {
                Expressions.BaseText bt = findResultList[findResultPoint];

                if (bt.Editor.SelectedExpression == bt && bt.Text.Contains(tbxFindText.Text))
                {
                    ModifingItem mi = new ModifingItem()
                    {
                        OldSelectedExID = bt.ExID
                    };

                    string replacedText = bt.Text.Replace(tbxFindText.Text, tbxReplaceText.Text);

                    Action actReplace = new Action(bt.ExID, -1, bt.GetType().Name,
                        "Text", bt.Text, replacedText);

                    bt.Text = replacedText;

                    mi.Add(actReplace);

                    bt.Editor.Do(mi);

                    Expressions.BaseText nextBt = FindNext();
                    if (nextBt != null)
                    {
                        mi.NewSelectedExID = nextBt.ExID;
                    }
                }
                else
                {
                    MessageBox.Show("替换时发现意外：准备替换的文本块未选中，或者此文本块不不包含要查找的内容。",
                        Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }
            else
            {
                MessageBox.Show("替换时发现意外：公式索引越界了。",
                        Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
        }
    }
}
